/*
 * Copyright 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hnly.djdl.home.p4

import android.util.Log
import android.widget.Toast
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.systemBarsPadding
import com.hnly.djdl.BuildConfig
import com.hnly.djdl.R
import com.hnly.djdl.model.HUrl
import com.hnly.djdl.components.CommonDialog
import com.hnly.djdl.components.TitleText
import com.hnly.djdl.components.TopHeader
import com.hnly.djdl.components.WebViewDialog
import com.hnly.djdl.theme.MainBackgroundColor
import com.hnly.djdl.theme.MainCardColor
import com.hnly.djdl.theme.MainTextColor
import com.hnly.djdl.theme.MainTheme
import com.hnly.djdl.theme.MainThemeColor

@Composable
fun P4Page(modifier: Modifier = Modifier) {
    var showAboutDialog by remember { mutableStateOf(false) }
    var showFeedBackDialog by remember { mutableStateOf(false) }
    var showAgreementDialog by remember { mutableStateOf(false) }
    var showPrivacyDialog by remember { mutableStateOf(false) }
    Column(
        verticalArrangement = Arrangement.Top,
        modifier = modifier
            .fillMaxSize()
            .background(MainBackgroundColor)
    ) {
        Box(modifier = Modifier.fillMaxWidth().height(260.dp)) {
            TopHeader(modifier = Modifier.height(200.dp))
            TitleText(
                text = stringResource(id = R.string.app_name), modifier = Modifier
                    .align(Alignment.TopCenter)
                    .systemBarsPadding(true)
            )
            Image(
                painter = painterResource(id = R.mipmap.ic_launcher),
                contentDescription = null,
                modifier.size(130.dp).align(Alignment.BottomCenter).clip(CircleShape)
            )
        }
        Spacer(modifier = Modifier.height(20.dp))
        val switchBtn = remember { mutableStateOf(true) }
//        ProfileItem(
//            iconId = R.drawable.profile_xieyi,
//            rightContent = {
//                Switch(
//                    checked = switchBtn.value,
//                    onCheckedChange = { value -> switchBtn.value = value },
//                    colors = SwitchDefaults.colors(
//                        uncheckedThumbColor = MainThemeColor,
//                        checkedThumbColor = MainThemeColor,
//                        checkedTrackColor = MainThemeColor,
//                        uncheckedTrackColor = MainThemeColor
//                    )
//                )
//            },
//            text = "个性化推荐"
//        ) {
//        }
        Spacer(modifier = Modifier.height(20.dp))

        ProfileItem(iconId = R.drawable.profile_yinsi, text = "隐私政策") {
            showPrivacyDialog = true
        }
        Spacer(modifier = Modifier.height(20.dp))
        ProfileItem(iconId = R.drawable.profile_xieyi, text = "用户协议") {
            showAgreementDialog = true
        }
        Spacer(modifier = Modifier.height(20.dp))
        ProfileItem(iconId = R.drawable.ic_account, text = "当前版本", rightContent = {
            Text(
                text = "v${BuildConfig.APP_VERSIONNAME}",
                style = TextStyle.Default.copy(color = MainTextColor)
            )
        }, onClick = {})
    }

    if (showAboutDialog) {
        AboutDialog(
            onDismissRequest = {
                showAboutDialog = false
            },
            onAgreement = {
                showAgreementDialog = true
            },
            onPrivacy = {
                showPrivacyDialog = true
            }
        )
    }
    if (showFeedBackDialog) {
        FeedBackDialog {
            showFeedBackDialog = false
        }
    }
    if (showAgreementDialog) {
        showPrivacyDialog = false
        WebViewDialog(url = HUrl.agreement()) {
            showAgreementDialog = false
        }
    }
    if (showPrivacyDialog) {
        showAgreementDialog = false
        WebViewDialog(url = HUrl.privacy()) {
            showPrivacyDialog = false
        }
    }
}

@Composable
fun ProfileItem(
    @DrawableRes iconId: Int, text: String,
    rightContent: @Composable RowScope.() -> Unit = {
        Image(
            painter = painterResource(id = android.R.drawable.arrow_down_float),
            contentDescription = null,
            modifier = Modifier.rotate(-90f),
            colorFilter = ColorFilter.tint(color = MainThemeColor)
        )
    },
    onClick: () -> Unit,
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .height(68.dp)
            .padding(horizontal = 14.dp)
            .clip(RoundedCornerShape(20.dp)),
        backgroundColor = Color.White
    ) {
        Row(
            modifier = Modifier
                .height(68.dp)
                .clickable(onClick = onClick)
                .background(MainCardColor)
                .padding(horizontal = 20.dp)
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(id = iconId),
                contentDescription = null,
                modifier = Modifier.size(20.dp),
                colorFilter = ColorFilter.tint(MainThemeColor),
            )
            Spacer(modifier = Modifier.width(20.dp))
            Text(text = text, style = TextStyle.Default.copy(color = MainTextColor))
            Spacer(modifier = Modifier.weight(1f))
            rightContent()
        }
    }

}

@Composable
fun SpannableAgreementPrivacyText(onAgreement: () -> Unit, onPrivacy: () -> Unit) {
    val style = SpanStyle(Color.Red, fontWeight = FontWeight.Bold)
    // 《用户协议》和《隐私政策》
    val annotatedString = buildAnnotatedString {
        pushStringAnnotation(tag = "agreement", annotation = "agreement")
        withStyle(style = style) {
            append("《用户协议》")
        }
        pop()
        append(" 和 ")
        pushStringAnnotation(tag = "privacy", annotation = "privacy")
        withStyle(style = style) {
            append("《隐私政策》")
        }
        pop()
    }
    ClickableText(text = annotatedString) { offset ->
        if (BuildConfig.DEBUG) {
            Log.i("SpannableAgreement", "offset -> $offset")
        }
        annotatedString.getStringAnnotations(tag = "agreement", start = offset, end = offset)
            .firstOrNull()?.let {
                onAgreement()
            }
        annotatedString.getStringAnnotations(tag = "privacy", start = offset, end = offset)
            .firstOrNull()?.let {
                onPrivacy()
            }
    }
    //BasicText(text = annotatedString)
}

@Composable
fun FeedBackDialog(onDismissRequest: () -> Unit) {
    var text by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    val context = LocalContext.current
    CommonDialog(onDismissRequest = onDismissRequest) {
        Column(
            modifier = Modifier
                .height(520.dp)
                .padding(16.dp)
                .fillMaxSize()
        ) {
            TextField(
                value = text,
                onValueChange = { newText -> text = newText },
                label = { Text("输入您宝贵的意见", style = TextStyle(color = Color.Gray)) },
                placeholder = { Text("") },
                maxLines = 400,
//                singleLine = true,
//                isError = text.length > 10, // Example: show error if text is longer than 10 characters
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp),
                shape = RoundedCornerShape(10.dp),
                colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = Color.Gray.copy(alpha = 0.1f),
                    focusedIndicatorColor = Color.White,
                    disabledIndicatorColor = Color.White,
                    errorIndicatorColor = Color.White,
                    unfocusedIndicatorColor = Color.White
                )
            )
            Spacer(modifier = Modifier.height(10.dp))
            TextField(
                value = email,
                onValueChange = { newText -> email = newText },
                label = { Text("请输入联系方式", style = TextStyle(color = Color.Gray)) },
                placeholder = { Text("") },
                maxLines = 400,
//                singleLine = true,
//                isError = text.length > 10, // Example: show error if text is longer than 10 characters
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(10.dp),
                colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = Color.Gray.copy(alpha = 0.1f),
                    focusedIndicatorColor = Color.White,
                    disabledIndicatorColor = Color.White,
                    errorIndicatorColor = Color.White,
                    unfocusedIndicatorColor = Color.White
                )
            )
            Spacer(modifier = Modifier.height(10.dp))
            Button(
                onClick = {
                    if (text.isEmpty() || email.isEmpty()) {
                        Toast.makeText(context, "请填写正确信息", Toast.LENGTH_SHORT).show()
                    } else {
                        onDismissRequest()
                        Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show()
                    }
                },
                modifier = Modifier.fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(backgroundColor = Color.Green),
                shape = RoundedCornerShape(1.dp),
            ) {
                Text(text = "提交", style = TextStyle(color = Color.White))
            }
        }
    }
}

@Composable
fun AboutDialog(onDismissRequest: () -> Unit, onAgreement: () -> Unit, onPrivacy: () -> Unit) {
    val version = BuildConfig.APP_VERSIONNAME //getAppVersionName(LocalContext.current)
    CommonDialog(onDismissRequest = onDismissRequest) {
        Column(
            modifier = Modifier
                .height(520.dp)
                .fillMaxSize()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.weight(1f))
            Image(
                painter = painterResource(id = R.mipmap.ic_launcher),
                contentDescription = null,
                modifier = Modifier.size(80.dp)
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = stringResource(id = R.string.app_name),
                style = TextStyle(color = Color.Black, fontWeight = FontWeight.Bold)
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "当前版本:${version}",
                style = TextStyle(color = Color.Gray)
            )
            Spacer(modifier = Modifier.weight(2f))
            SpannableAgreementPrivacyText(onAgreement = onAgreement, onPrivacy = onPrivacy)
            Spacer(modifier = Modifier.height(10.dp))
            Text(text = "赵健")
            Spacer(modifier = Modifier.height(10.dp))
            Text(text = "@All Rights Resvered.")
        }
    }
}

@Preview("default")
@Composable
fun ProfileItemPreview() {
    MainTheme {
        ProfileItem(iconId = R.drawable.profile_fankui, text = "helo", onClick = {})
    }
}

@Preview("default")
@Composable
fun P4PagePreview() {
    MainTheme {
        P4Page()
    }
}
